@page
@model CreateApplicationModel

@{
    ViewData["Title"] = "New App";
}

<Feedback name="_error" LinkUrl="@Url.PageLink("/Billing/Manage")" LinkText="Upgrade" asp-if="!Model.CanCreateApplication"
          message="You need to upgrade to a paid organization to create more applications" />
<div id="app" class="sm:w-full sm:max-w-md">
    <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
        <form class="space-y-6" action="" method="POST">
            <div>
                <label asp-for="Form.Name" class="form-label">Application name</label>
                <div class="mt-2">
                    <input asp-for="Form.Name" v-model="appId" type="text" class="text-input">
                    <div v-cloak :class="{ invisible: !appId }" class=" small">
                        <input asp-for="Form.Id" type="hidden" :value="parsedAppId"/>
                        Your app id is:
                        <span class="parsed_tenant_name">{{parsedAppId}}</span>
                        <span v-if="availability == 'available'"> ✅ Available</span>
                        <span v-if="availability == 'not-available'"> ⚠️ Unavailable</span>

                    </div>
                    <span asp-validation-for="Form.Name"></span>
                </div>
            </div>
    
            <div>
                <label asp-for="Form.Description" class="form-label">Description</label>
                <div class="mt-2">
                    <input type="text" asp-for="Form.Description" class="text-input">
                    <span asp-validation-for="Form.Description"></span>
                </div>
            </div>

            <div asp-if="Model.Organization.HasSubscription">
                <label asp-for="Form.Plan" class="form-label">Plan</label>
                <ul class="radio-horizontal mt-2">
                    @foreach (var availablePlan in Model.AvailablePlans)
                    {
                        <li>
                            <div>
                                <input id="@availablePlan.Id" name="Form.Plan" type="radio" value="@availablePlan.Id" checked="@(Model.Form.Plan == availablePlan.Id)">
                                <label for="@availablePlan.Id">@availablePlan.Label</label>
                            </div>
                        </li>
                    }
                </ul>
                <info-alert-box variant="ColorVariant.Info" message="The application can always be assigned to a different plan later in the 'Billing' section."></info-alert-box>
            </div>
            <input asp-if="!Model.Organization.HasSubscription" type="hidden" asp-for="Form.Plan" />

            <div>
                <div asp-validation-summary="All"></div>
                <button type="submit"
                        :disabled="availability !== 'available'"
                        class="flex w-full justify-center rounded-md bg-primary-500 py-2 px-3 text-sm font-semibold text-white shadow-sm hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600">
                    Create
                </button>
            </div>
        </form>
    </div>
</div>


@section Scripts {
    <script type="module">
    import { createApp, computed, ref, watch } from 'vue';

    createApp({
        setup() {
            const appId = ref("");
            const availability = ref("");

            const parsedAppId = computed(() => {
                // parse string to to be alphanumeric and start with a letter. Between 3 - 50 length
                let clean = appId.value.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
                if (clean.length < 1)
                    return '';

                let firstChar = clean.charAt(0);
                if (!firstChar.match(/[a-z]/i)) {
                    firstChar = "x"
                }

                return firstChar + clean.slice(1);
            });

            const checkAvailability = async (appId) => {
                let res = await fetch(`/Applications/${appId}/Available`, {
                    method: "GET",
                    headers: {
                        "Content-Type": "application/json",
                    }
                });
                const data = await res.json();
                if (!res.ok) {
                    console.error("An unexpected error occurred. Cannot verify whether appid is available.")
                    return false;
                }
                return data.available === true;
            }

            watch(appId, async () => {
                if (parsedAppId.value.length < 3) {
                    availability.value = "not-available";
                    return;
                }
                const available = await checkAvailability(parsedAppId.value);
                availability.value = available ? "available" : "not-available";
            })

            return {
                appId,
                availability,
                parsedAppId
            }
        }
    }).mount("#app")
</script>
}